<template>
  <el-drawer
    :title="
      drawer.type === 'edit'
        ? '编辑'
        : drawer.type === 'new'
        ? '新增活动'
        : '活动详情'
    "
    :visible.sync="drawer.show"
    custom-class="add-drawer"
    ref="drawer"
    size="80%"
    :before-close="handleClose"
  >
    <div class="demo-drawer__content">
      <el-form
        v-if="ruleData"
        :model="ruleData"
        :rules="ruleDataRules"
        ref="ruleDataFormRef"
        style="padding: 0rem 2rem"
        label-position="top"
        label-width="100px"
      >
        <h2 class="title_line">所属油站</h2>

        <el-form-item prop="enterpriseId" label="油企选择" v-if="authUser">
          <el-select
            v-model="ruleData.enterpriseId"
            placeholder="请选择油企"
            size="small"
            filterable
            clearable
            :disabled="drawer.type === 'view'"
            style="width: 100%"
            @change="handleSelectChange"
          >
            <el-option
              v-for="(item, index) in settingData.enterpriseList"
              :key="index"
              :label="item.enterpriseName"
              :value="item.enterpriseId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="stationId" label="油站选择">
          <el-select
            v-model="ruleData.stationId"
            placeholder="请选择油站"
            size="small"
            filterable
            clearable
            :disabled="drawer.type === 'view'"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in settingData.stationList"
              :key="index"
              :label="item.stationName"
              :value="item.stationId"
            ></el-option>
          </el-select>
        </el-form-item>

        <h2 class="title_line radio-activity">活动形式</h2>
        <el-form-item prop="activityMode">
          <el-radio-group
            v-model="ruleData.activityMode"
            size="medium"
            @input="inputRadioActivity"
          >
            <el-radio-button
              :disabled="drawer.type === 'view'"
              label="recharge"
              class="radio-button"
              >充值</el-radio-button
            >
            <el-radio-button
              :disabled="drawer.type === 'view'"
              label="consume"
              class="radio-button"
              >消费</el-radio-button
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item label="参与活动支付方式" v-show="isCharge" prop="payMode">
          <label slot="label">
            <span style="color: red" v-show="isCharge === true">*</span>
            参与活动支付方式
          </label>
          <el-checkbox-group
            v-model="payMode"
            size="medium"
            @change="inputRadioMethodPayment"
          >
            <el-checkbox-button
              :disabled="drawer.type === 'view'"
              v-for="item in citiesPayment"
              :label="item.value"
              :key="item.text"
              >{{ item.text }}</el-checkbox-button
            >
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="电子卡类型" prop="cardType">
          <el-checkbox-group v-model="cardTypeList">
            <el-checkbox-button
              v-for="v of cardOilsTypeList"
              :disabled="drawer.type === 'view'"
              :label="v"
              :key="v"
            >
              {{ formmatType(v) }}
            </el-checkbox-button>
            <!-- <el-checkbox-button
              label="1"
              key="1"
              :disabled="drawer.type === 'view'"
              >汽油卡</el-checkbox-button
            >
            <el-checkbox-button
              label="2"
              key="2"
              :disabled="drawer.type === 'view'"
              >柴油卡</el-checkbox-button
            >
            <el-checkbox-button
              label="4"
              key="4"
              :disabled="drawer.type === 'view'"
              >LNG</el-checkbox-button
            >
            <el-checkbox-button
              label="5"
              key="5"
              :disabled="drawer.type === 'view'"
              >CNG</el-checkbox-button
            >

            <el-checkbox-button
              label="0"
              key="0"
              :disabled="drawer.type === 'view'"
            >
              通用卡
            </el-checkbox-button> -->
          </el-checkbox-group>
        </el-form-item>

        <!-- 1、活动形式：充值  -->
        <div v-if="isCharge">
          <h2 class="title_line">活动设置</h2>
          <el-form-item prop="activityType" label="活动类型">
            <el-select
              v-model="ruleData.activityType"
              placeholder="请选择活动类型"
              size="small"
              clearable
              :disabled="drawer.type === 'view'"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in activityTypeList"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 活动内容：属于赠送优惠券、赠送积分 类型才会显示 -->
          <el-form-item
            label="活动内容"
            v-if="ruleData.activityType === 'coupon'"
          >
            <el-row
              v-for="(item, index) in ruleData.contentList"
              :key="index"
              style="margin-bottom: 20px"
            >
              <el-col :span="5">
                <el-form-item
                  style="display: inline-block"
                  :prop="`contentList[${index}].rechargeAmtLowerLimit`"
                  :rules="ruleDataRules.contentList.rechargeAmtLowerLimit"
                >
                  <el-input-number
                    :min="0"
                    :precision="2"
                    :step="0.1"
                    :disabled="drawer.type === 'view'"
                    v-model="item.rechargeAmtLowerLimit"
                    placeholder="请输入"
                    style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="3" style="text-align: center">
                <span>≤充值金额(元)＜</span>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  style="display: inline-block"
                  :prop="`contentList[${index}].rechargeAmtUpperLimit`"
                  :rules="ruleDataRules.contentList.rechargeAmtUpperLimit"
                >
                  <el-input-number
                    :min="0"
                    :precision="2"
                    :step="0.1"
                    :disabled="drawer.type === 'view'"
                    v-model="item.rechargeAmtUpperLimit"
                    placeholder="请输入"
                    style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="3" style="text-align: center">
                <span>，赠送优惠券</span>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  style="display: inline-block"
                  :prop="`contentList[${index}].couponIssueId`"
                  :rules="ruleDataRules.contentList.couponIssueId"
                >
                  <el-select
                    :disabled="drawer.type === 'view'"
                    v-model="item.couponIssueId"
                    placeholder="请选择"
                    style="width: 100%"
                    multiple
                    filterable
                    :collapse-tags="drawer.type !== 'view'"
                  >
                    <el-option
                      v-for="item in settingData.couponList"
                      :key="item.id"
                      :label="item.couponRemark"
                      :value="item.id"
                    >
                      <span style="float: left">{{ item.couponRemark }}</span>
                      <span
                        style="float: right; color: #8492a6; font-size: 13px"
                        >{{ item.id }}</span
                      >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col
                v-if="drawer.type != 'view'"
                :span="2"
                style="
                  display: flex;
                  flex-direction: row;
                  align-items: center;
                  height: 40px;
                  margin-left: 10px;
                "
              >
                <el-button
                  v-if="index != 0 || ruleData.contentList.length > 1"
                  type="danger"
                  icon="el-icon-minus"
                  circle
                  size="mini"
                  @click="contentListDel(index)"
                ></el-button>
                <el-button
                  v-if="index + 1 === ruleData.contentList.length"
                  type="primary"
                  size="mini"
                  icon="el-icon-plus"
                  circle
                  @click="contentListAdd(index)"
                ></el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <!--赠送方式 ： 选择了赠送电子卡余额 才显示  -->
          <el-form-item
            label="赠送方式"
            prop="settingRuleType"
            v-if="ruleData.activityType === 'balance'"
          >
            <el-select
              v-model="ruleData.settingRuleType"
              placeholder="请选择赠送方式"
              size="small"
              clearable
              :disabled="drawer.type === 'view'"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in settingRuleTypeList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!--  活动内容： 选择了 赠送优惠券 和赠送积分 才能设置活动内容 -->
          <el-form-item
            label="活动内容"
            v-if="
              (['1', '2'].includes(ruleData.settingRuleType) &&
                ruleData.activityType === 'balance') ||
              ruleData.activityType === 'integral'
            "
          >
            <el-row
              v-for="(item, index) in ruleData.contentList"
              :key="index"
              style="margin-bottom: 20px"
            >
              <el-col :span="5">
                <el-form-item
                  style="display: inline-block"
                  :prop="`contentList[${index}].rechargeAmtLowerLimit`"
                  :rules="ruleDataRules.contentList.rechargeAmtLowerLimit"
                >
                  <el-input-number
                    :min="0"
                    :max="99999999999"
                    :precision="2"
                    :step="0.1"
                    :disabled="drawer.type === 'view'"
                    v-model="item.rechargeAmtLowerLimit"
                    placeholder="请输入"
                    style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="3" style="text-align: center">
                <span>≤金额(元)＜</span>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  style="display: inline-block"
                  :prop="`contentList[${index}].rechargeAmtUpperLimit`"
                  :rules="ruleDataRules.contentList.rechargeAmtUpperLimit"
                >
                  <el-input-number
                    :min="0"
                    :max="99999999999"
                    :precision="2"
                    :step="0.1"
                    :disabled="drawer.type === 'view'"
                    v-model="item.rechargeAmtUpperLimit"
                    placeholder="请输入"
                    style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col
                v-if="ruleData.activityType !== 'integral'"
                :span="3"
                style="text-align: center"
              >
                <span>，赠送</span>
              </el-col>
              <el-col v-else :span="3" style="text-align: center">
                <span>，每充值1元赠送</span>
              </el-col>
              <el-col :span="4">
                <el-form-item
                  style="display: inline-block"
                  :prop="`contentList[${index}].presentAmount`"
                  :rules="ruleDataRules.contentList.presentAmount"
                >
                  <el-input-number
                    :min="0"
                    :max="99999999999"
                    v-if="ruleData.activityType !== 'integral'"
                    :disabled="drawer.type === 'view'"
                    v-model="item.presentAmount"
                    placeholder="请输入"
                    style="width: 100%"
                  ></el-input-number>
                  <el-input-number
                    v-else
                    :controls="false"
                    :min="0"
                    :max="99999999999"
                    :disabled="drawer.type === 'view'"
                    v-model="item.presentAmount"
                    placeholder="请输入"
                    style="width: 100%"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col
                v-if="ruleData.activityType !== 'integral'"
                :span="1"
                style="margin-left: 5px"
              >
                <span v-if="ruleData.settingRuleType === '1'">元</span>
                <span v-else>%</span>
              </el-col>
              <el-col v-else :span="1" style="margin-left: 5px">
                <span>积分</span>
              </el-col>
              <el-col
                v-if="drawer.type != 'view'"
                :span="2"
                style="
                  display: flex;
                  flex-direction: row;
                  align-items: center;
                  height: 40px;
                  margin-left: 10px;
                "
              >
                <el-button
                  v-if="index != 0 || ruleData.contentList.length > 1"
                  type="danger"
                  icon="el-icon-minus"
                  circle
                  size="mini"
                  @click="contentListDel(index)"
                ></el-button>
                <el-button
                  v-if="index + 1 === ruleData.contentList.length"
                  type="primary"
                  size="mini"
                  icon="el-icon-plus"
                  circle
                  @click="contentListAdd(index)"
                ></el-button>
              </el-col>
            </el-row>
          </el-form-item>

          <!-- 活动时间范围 -->
          <el-form-item label="活动时间范围" prop="activityTimeRange">
            <el-date-picker
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="timeSetting.activityTimeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              style="width: 100%"
              :disabled="drawer.type === 'view'"
            >
            </el-date-picker>
          </el-form-item>
          <!-- 生效时间设置 -->
          <el-form-item
            label="生效时间设置"
            prop="periodType"
            class="numberBtn"
          >
            <p class="t">
              生效时段
              <el-checkbox-group
                v-model="timeSetting.periodType"
                @change="changeTimeMode"
              >
                <el-checkbox
                  class="block"
                  label="all"
                  :disabled="
                    timeSetting.periodType.includes('week') ||
                    timeSetting.periodType.includes('month') ||
                    drawer.type === 'view'
                  "
                >
                  全部时段
                </el-checkbox>
                <el-checkbox
                  class="block"
                  label="week"
                  :disabled="
                    timeSetting.periodType.includes('all') ||
                    drawer.type === 'view'
                  "
                >
                  按周选择
                  <div
                    style="
                      padding: 20px 20px 0 20px;
                      display: inline-block;
                      width: 100%;
                    "
                    v-show="timeSetting.periodType.includes('week')"
                  >
                    <el-checkbox-group
                      v-model="timeSetting.weeks"
                      size="medium"
                    >
                      <el-checkbox-button
                        v-for="day in 7"
                        :label="day"
                        :key="day"
                        :disabled="drawer.type === 'view'"
                        >{{ day }}
                      </el-checkbox-button>
                    </el-checkbox-group>
                  </div>
                </el-checkbox>
                <div v-show="timeSetting.periodType.includes('week')" style="display: flex;">
                  <span class="title1">
                    <b style="color: red">*</b>生效时间
                  </span>
                  <template>
                    <el-time-picker
                      value-format="HH:mm:ss"
                      is-range
                      size="mini"
                      v-model="timeSetting.weeksTime"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      placeholder="选择时间范围"
                      :disabled="drawer.type === 'view'"
                    ></el-time-picker>
                  </template>
                  <div style="margin-left: 2rem">
                    <el-radio-group v-model="timeSetting.weekTimeRangeType">
                      <el-radio label="each">按天执行</el-radio>
                      <el-radio label="entire">按最后一天执行</el-radio>
                    </el-radio-group>
                </div>
                </div>

                <el-checkbox
                  class="block"
                  label="month"
                  :disabled="
                    timeSetting.periodType.includes('all') ||
                    drawer.type === 'view'
                  "
                >
                  按月选择
                  <div
                    style="padding: 20px 20px 0 20px; display: inline-block"
                    v-show="timeSetting.periodType.includes('month')"
                  >
                    <el-checkbox-group v-model="timeSetting.days" size="medium">
                      <el-checkbox-button
                        v-for="day in 31"
                        :label="day"
                        :key="day"
                        :disabled="drawer.type === 'view'"
                        >{{ day }}
                      </el-checkbox-button>
                    </el-checkbox-group>
                  </div>
                </el-checkbox>
                <div v-show="timeSetting.periodType.includes('month')" style="display: flex;" >
                  <span class="title1">
                    <b style="color: red">*</b>生效时间
                  </span>
                  <template>
                    <el-time-picker
                      value-format="HH:mm:ss"
                      is-range
                      size="mini"
                      v-model="timeSetting.daysTime"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      placeholder="选择时间范围"
                      :disabled="drawer.type === 'view'"
                    ></el-time-picker>
                  </template>
                  <div style="margin-left: 2rem">
                    <el-radio-group v-model="timeSetting.monthTimeRangeType">
                      <el-radio label="each">按天执行</el-radio>
                      <el-radio label="entire">按最后一天执行</el-radio>
                    </el-radio-group>
                  </div>
                </div>
              </el-checkbox-group>
            </p>
          </el-form-item>

          <!-- 是否发送活动 -->
          <el-form-item
            label="是否发送活动通知"
            style="margin-bottom: 0 !important"
            prop="sendFlag"
          >
            <el-radio-group v-model="ruleData.sendFlag">
              <el-radio :disabled="drawer.type === 'view'" :label="1"
                >是</el-radio
              >
              <el-radio :disabled="drawer.type === 'view'" :label="0"
                >否</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="wxContent" v-if="ruleData.sendFlag === 1">
            <el-input
              :disabled="drawer.type === 'view'"
              v-model="ruleData.wxContent"
              size="small"
              maxlength="20"
              show-word-limit
              placeholder="推送内容仅限20个字"
              style="width: 400px; display: block"
            ></el-input>
          </el-form-item>
          <el-form-item style="text-align: end">
            <div class="demo-drawer__footer">
              <el-button @click="handleClose">取消</el-button>
              <el-button
                v-if="drawer.type === 'edit'"
                type="primary"
                @click="handleSubmitEdit"
                >提交</el-button
              >
              <el-button
                v-if="drawer.type === 'new'"
                type="primary"
                @click="handleSubmitAdd"
                >提交</el-button
              >
            </div>
          </el-form-item>
        </div>
        <!-- 2、活动形式：消费 -->
        <div v-else>
          <el-form
            :model="formConsumption"
            :rules="formConsumptionRules"
            ref="formConsumptionRef"
          >
            <el-form-item label="活动方式">
              <label slot="label">
                <span style="color: red">*</span> 活动方式
              </label>
              <div>
                <span class="span-text">按金额</span>
                <el-switch
                  :disabled="drawer.type === 'view'"
                  v-model="amount"
                  @change="changeAmount"
                >
                </el-switch>
              </div>
              <span class="span-text">按升数</span>
              <el-switch
                :disabled="drawer.type === 'view'"
                v-model="litres"
                @change="changeLitres"
              >
              </el-switch>
            </el-form-item>
            <el-form-item label="赠送方式" prop="settingRuleType">
              <el-select
                :disabled="drawer.type === 'view'"
                style="width: 100%"
                size="small"
                v-model="formConsumption.settingRuleType"
                placeholder="请选择活动区域"
              >
                <el-option label="按金额赠送" value="1"></el-option>
                <el-option label="按比例赠送" value="2"></el-option>
              </el-select>
            </el-form-item>

            <div v-show="(amount || litres) && formConsumption.settingRuleType">
              <div class="span-div">
                <div class="span-div-qj">消费区间</div>
                <div>赠送金额</div>
              </div>
              <div
                class="span-div"
                v-for="(item, index) in formConsumption.contentList"
              >
                <el-form-item
                  :rules="
                    formConsumptionRules.contentList.rechargeAmtLowerLimit
                  "
                  :prop="`contentList[${index}].rechargeAmtLowerLimit`"
                >
                  <el-input-number
                    style="width: 210px"
                    v-model="item.rechargeAmtLowerLimit"
                    :disabled="drawer.type === 'view'"
                    :precision="2"
                    :step="0.1"
                    placeholder="请输入"
                  ></el-input-number>
                </el-form-item>
                <span class="span-yang">
                  {{ formConsumption.accordingTo === "amount" ? "元 ——" : "" }}
                  {{ formConsumption.accordingTo === "litres" ? "升 ——" : "" }}
                </span>

                <el-form-item
                  :rules="
                    formConsumptionRules.contentList.rechargeAmtUpperLimit
                  "
                  :prop="`contentList[${index}].rechargeAmtUpperLimit`"
                >
                  <el-input-number
                    style="width: 210px"
                    v-model="item.rechargeAmtUpperLimit"
                    :precision="2"
                    :step="0.1"
                    :disabled="drawer.type === 'view'"
                    placeholder="请输入"
                  ></el-input-number>
                </el-form-item>
                <span class="span-yan">
                  {{ formConsumption.accordingTo === "amount" ? "元" : "" }}
                  {{ formConsumption.accordingTo === "litres" ? "升" : "" }}
                </span>
                <el-form-item
                  :rules="formConsumptionRules.contentList.presentAmount"
                  :prop="`contentList[${index}].presentAmount`"
                >
                  <el-input-number
                    style="width: 210px"
                    v-model="item.presentAmount"
                    :precision="2"
                    :step="0.1"
                    :disabled="drawer.type === 'view'"
                    placeholder="请输入"
                  ></el-input-number>
                  <span style="margin: 0px 10px">{{
                    formConsumption.settingRuleType === "1" ? "元" : "%"
                  }}</span>
                </el-form-item>
                <el-form-item>
                  <el-button
                    :disabled="drawer.type === 'view'"
                    size="medium"
                    type="primary"
                    @click="addContentList"
                    style="margin-left: 15px"
                    v-show="index === formConsumption.contentList.length - 1"
                    >增加</el-button
                  >
                  <el-button
                    :disabled="drawer.type === 'view'"
                    size="medium"
                    @click="popContentList"
                    v-show="formConsumption.contentList.length !== 1"
                    >删除</el-button
                  >
                </el-form-item>
              </div>
            </div>
            <h2 class="title_line">活动设置</h2>
            <!-- 活动时间范围 -->
            <el-form-item label="活动时间范围" prop="activityTimeRange">
              <el-date-picker
                value-format="yyyy-MM-dd HH:mm:ss"
                v-model="timeSetting.activityTimeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="small"
                style="width: 100%"
                :disabled="drawer.type === 'view'"
              >
              </el-date-picker>
            </el-form-item>
            <!-- 生效时间设置 -->
            <el-form-item
              label="生效时间设置"
              prop="periodType"
              class="numberBtn"
            >
              <p class="t">
                生效时段
                <el-checkbox-group
                  v-model="timeSetting.periodType"
                  @change="changeTimeMode"
                >
                  <el-checkbox
                    class="block"
                    label="all"
                    :disabled="
                      timeSetting.periodType.includes('week') ||
                      timeSetting.periodType.includes('month') ||
                      drawer.type === 'view'
                    "
                  >
                    全部时段
                  </el-checkbox>
                  <el-checkbox
                    class="block"
                    label="week"
                    :disabled="timeSetting.periodType.includes('all')"
                  >
                    按周选择
                    <div
                      style="
                        padding: 20px 20px 0 20px;
                        display: inline-block;
                        width: 100%;
                      "
                      v-show="timeSetting.periodType.includes('week')"
                    >
                      <el-checkbox-group
                        v-model="timeSetting.weeks"
                        size="medium"
                      >
                        <el-checkbox-button
                          v-for="day in 7"
                          :label="day"
                          :key="day"
                          :disabled="drawer.type === 'view'"
                          >{{ day }}
                        </el-checkbox-button>
                      </el-checkbox-group>
                    </div>
                  </el-checkbox>
                  <div v-show="timeSetting.periodType.includes('week')" style="display: flex;">
                    <span class="title1">
                      <b style="color: red">*</b>生效时间
                    </span>
                    <template>
                      <el-time-picker
                        value-format="HH:mm:ss"
                        is-range
                        size="mini"
                        v-model="timeSetting.weeksTime"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        placeholder="选择时间范围"
                        :disabled="drawer.type === 'view'"
                      ></el-time-picker>
                    </template>
                    <div style="margin-left: 2rem">
                    <el-radio-group v-model="timeSetting.weekTimeRangeType">
                      <el-radio label="each">按天执行</el-radio>
                      <el-radio label="entire">按最后一天执行</el-radio>
                    </el-radio-group>
                </div>
                  </div>

                  <el-checkbox
                    class="block"
                    label="month"
                    :disabled="
                      timeSetting.periodType.includes('all') ||
                      drawer.type === 'view'
                    "
                  >
                    按月选择
                    <div
                      style="padding: 20px 20px 0 20px; display: inline-block"
                      v-show="timeSetting.periodType.includes('month')"
                    >
                      <el-checkbox-group
                        v-model="timeSetting.days"
                        size="medium"
                      >
                        <el-checkbox-button
                          v-for="day in 31"
                          :label="day"
                          :key="day"
                          :disabled="drawer.type === 'view'"
                          >{{ day }}
                        </el-checkbox-button>
                      </el-checkbox-group>
                    </div>
                  </el-checkbox>
                  <div v-show="timeSetting.periodType.includes('month')" style="display: flex;">
                    <span class="title1">
                      <b style="color: red">*</b>生效时间
                    </span>
                    <template>
                      <el-time-picker
                        value-format="HH:mm:ss"
                        is-range
                        size="mini"
                        v-model="timeSetting.daysTime"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        placeholder="选择时间范围"
                        :disabled="drawer.type === 'view'"
                      ></el-time-picker>
                    </template>
                    <div style="margin-left: 2rem">
                    <el-radio-group v-model="timeSetting.weekTimeRangeType">
                      <el-radio label="each">按天执行</el-radio>
                      <el-radio label="entire">按最后一天执行</el-radio>
                    </el-radio-group>
                </div>
                  </div>
                </el-checkbox-group>
              </p>
            </el-form-item>

            <div>
              <el-form-item style="text-align: end">
                <div class="demo-drawer__footer">
                  <el-button @click="consumptionHandleClone">取消</el-button>
                  <el-button
                    v-if="drawer.type === 'new'"
                    type="primary"
                    @click="consumptionHandleAdd"
                    >提交</el-button
                  >
                </div>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-form>
    </div>
  </el-drawer>
</template>
<script>
import { cloneDeep } from "lodash";
import { listEnterpriseStation } from "@/api/dept";
import {
  customerDetail,
  addConsumeActivity,
  selectCustomerCardSetting,
} from "@/api/customer/cardSetting";

const cityOptionsPayment = [
  { text: "微信", value: "wx" },
  { text: "手动添加", value: "xj" },
];

export default {
  props: {
    parm: {
      type: Object,
      default: null,
    },
  },
  data() {
    // 参与支付方式校验
    var validatePass = (rule, value, callback) => {
      if (this.payMode.length === 0) {
        callback(new Error("请选择参与活动支付方式"));
      } else {
        callback();
      }
    };
    var validateNum = (rule, value, callback) => {
      let decimal = this.isDecimal(value);
      if (decimal.y > 2 && decimal.x != 0) {
        callback(new Error("最多输入两位小数"));
      }
      callback();
    };
    var validateMinRuleData = (rule, value, callback) => {
      const max =
        this.ruleData.contentList[rule.field[12]].rechargeAmtUpperLimit;

      if (value >= max) {
        callback(new Error("开始金额不能大于结束金额"));
      }

      let decimal = this.isDecimal(value);
      if (decimal.y > 2 && decimal.x != 0) {
        callback(new Error("最多输入两位小数"));
      }
      callback();
    };
    var validateMaxRuleData = (rule, value, callback) => {
      const min =
        this.ruleData.contentList[rule.field[12]].rechargeAmtLowerLimit;
      if (value <= min) {
        callback(new Error("结束金额不能小于开始金额"));
      }

      let decimal = this.isDecimal(value);
      if (decimal.y > 2 && decimal.x != 0) {
        callback(new Error("最多输入两位小数"));
      }
      callback();
    };
    var validateMin = (rule, value, callback) => {
      const max =
        this.formConsumption.contentList[rule.field[12]].rechargeAmtUpperLimit;

      if (value >= max) {
        callback(new Error("开始区间不能大于结束区间"));
      }

      let decimal = this.isDecimal(value);
      if (decimal.y > 2 && decimal.x != 0) {
        callback(new Error("最多输入两位小数"));
      }
      callback();
    };
    var validateMax = (rule, value, callback) => {
      const min =
        this.formConsumption.contentList[rule.field[12]].rechargeAmtLowerLimit;
      if (value <= min) {
        callback(new Error("结束区间不能小于开始区间"));
      }

      let decimal = this.isDecimal(value);
      if (decimal.y > 2 && decimal.x != 0) {
        callback(new Error("最多输入两位小数"));
      }
      callback();
    };
    // 校验电子卡类型
    let validateCardType = (rule, value, callback) => {
      if (!this.cardTypeList.length) {
        return callback(new Error("请选择电子卡类型"));
      } else {
        return callback();
      }
    };
    // 校验活动时间范围
    let validateActivityTimeRange = (rule, value, callback) => {
      // console.log("校验活动时间范围");
      if (this.timeSetting.activityTimeRange.length) {
        return callback();
      } else {
        return callback(new Error("请选择活动时间范围"));
      }
    };
    // 校验生效时间设置
    var validateTimeModes = (rule, value, callback) => {
      if (this.timeSetting.periodType.length == 0) {
        callback(new Error("生效时段不能为空"));
      }
      if (this.timeSetting.periodType.includes("week")) {
        if (!this.timeSetting.weeksTime || this.timeSetting.weeks.length == 0) {
          callback(new Error("请选择周生效时间"));
        }
      }
      if (this.timeSetting.periodType.includes("month")) {
        if (!this.timeSetting.daysTime || this.timeSetting.days.length == 0) {
          callback(new Error("请选择月生效时间"));
        }
      }
      callback();
    };

    return {
      cardOilsTypeList: [],
      amount: true,
      litres: false,
      // 消费
      formConsumption: {
        accordingTo: "amount",
        settingRuleType: "",
        contentList: [
          {
            presentAmount: undefined,
            rechargeAmtLowerLimit: undefined,
            rechargeAmtUpperLimit: undefined,
          },
        ],
      },
      // 消费的表单校验规则
      formConsumptionRules: {
        settingRuleType: [
          { required: true, message: "请选择活动区域", trigger: "change" },
        ],
        // 活动时间范围
        activityTimeRange: [
          {
            required: true,
            validator: validateActivityTimeRange,
            trigger: "change",
          },
        ],
        // 生效时间设置
        periodType: [
          { required: true, validator: validateTimeModes, trigger: "change" },
        ],
        contentList: {
          rechargeAmtLowerLimit: [
            { required: true, message: "请输入" },
            { validator: validateMin },
          ],
          rechargeAmtUpperLimit: [
            { required: true, message: "请输入" },
            { validator: validateMax },
          ],
          presentAmount: [
            { required: true, message: "请输入" },
            { validator: validateNum },
          ],
        },
      },

      isCharge: true, // true ： 充值   false 消费
      payMode: [], // 参与活动方式

      citiesPayment: cityOptionsPayment,
      drawer: {
        show: this.parm ? this.parm.drawerShow : false,
        type: this.parm ? this.parm.drawerType : "read", // edit || view || new
      },
      ruleData: this.parm ? this.parm.ruleData : {},
      settingData: this.parm ? this.parm.settingData : {},
      // 表单校验
      ruleDataRules: {
        enterpriseId: [
          { required: true, message: "请选择油企", trigger: "change" },
        ],
        stationId: [
          { required: true, message: "请选择油站", trigger: "change" },
        ],
        activityType: [
          { required: true, message: "请选择活动类型", trigger: "change" },
        ],
        settingRuleType: [
          { required: true, message: "请选择赠送方式", trigger: "change" },
        ],

        // 活动时间范围
        activityTimeRange: [
          {
            required: true,
            validator: validateActivityTimeRange,
            trigger: "change",
          },
        ],
        // 生效时间设置
        periodType: [
          { required: true, validator: validateTimeModes, trigger: "change" },
        ],
        // 赠送规则列表
        contentList: {
          rechargeAmtLowerLimit: [
            { required: true, message: "请输入", trigger: "blur" },
            { validator: validateMinRuleData, trigger: "change" },
          ],
          rechargeAmtUpperLimit: [
            { required: true, message: "请输入", trigger: "blur" },
            { validator: validateMaxRuleData, trigger: "change" },
          ],
          presentAmount: [
            { required: true, message: "请输入", trigger: "blur" },
            { validator: validateNum, trigger: "blur" },
          ],
          couponIssueId: [
            { required: true, message: "请选择优惠券", trigger: "blur" },
          ],
        },
        sendFlag: [
          { required: true, message: "请选择是否发送", trigger: "change" },
        ],
        wxContent: [
          { required: true, message: "请输入推送内容", trigger: "blur" },
        ],
        payMode: [{ validator: validatePass, trigger: "blur" }],
        cardType: [
          { required: true, validator: validateCardType, trigger: "change" },
        ],
        activityMode: [
          { required: true, message: "请选择活动形式", trigger: "blur" },
        ],
      },
      activityTypeList: [
        {
          label: "赠送电子卡金额",
          value: "balance",
        },
        {
          label: "赠送优惠券",
          value: "coupon",
        },
        {
          label: "赠送积分",
          value: "integral",
        },
      ],
      settingRuleTypeList: [
        {
          label: "赠送金额",
          value: "1",
        },
        {
          label: "赠送比例",
          value: "2",
        },
      ],
      cardTypeList: [], // 电子卡类型数组

      // 活动时间设置
      timeSetting: {
        monthTimeRangeType: 'each',// 月
        weekTimeRangeType: 'each', // 周
        activityTimeRange: [], // 活动时间范围
        periodType: ["all"], // 时段类型  all：全部  ；   week：按周  month按月
        weeks: [], // 按周选择保存周一 到 周日
        weeksTime: "", // 按周生效时间范围
        days: [], // 保存 按月选择的 1-31号的
        daysTime: "", // 按月选择的生效时间范围
      },
    };
  },
  computed: {
    authUser() {
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
  },
  created() {
    this.init();
  },
  watch: {
    parm(newValue) {
      // console.log("查看新增---parm", newValue);
      this.drawer.show = newValue.drawerShow;
      this.drawer.type = newValue.drawerType;
      this.ruleData = newValue.ruleData;
      this.settingData = newValue.settingData;

      // 新增 :  默认选中充值 , 单个油站直接显示
      if (newValue.drawerType === "new") {
        this.ruleData.activityMode = "recharge";
        if (newValue.settingData.stationList.length === 1) {
          this.ruleData.stationId =
            newValue.settingData.stationList[0].stationId;
        }
      } else {
        // 查看
        if (this.ruleData.activityMode === "recharge") {
          // console.log("充值活动");
          this.ruleData.activityMode = "recharge";
          let checkList = newValue.ruleData.payType?.split(",");
          if (checkList) {
            checkList.forEach((res) => {
              this.payMode?.push(res);
            });
          }
          this.isCharge = true;
        } else if (this.ruleData.activityMode === "consume") {
          // console.log("消费活动");
          this.isCharge = false;
          this.formConsumption.contentList = newValue.ruleData.contentList;
          this.formConsumption.settingRuleType =
            newValue.ruleData.settingRuleType;
          this.ruleData.activityMode = "consume";

          if (newValue.ruleData.accordingTo === "amount") {
            this.formConsumption.accordingTo = "amount";
            this.amount = true;
            this.litres = false;
          } else if (newValue.ruleData.accordingTo === "litres") {
            this.formConsumption.accordingTo = "litres";
            this.amount = false;
            this.litres = true;
          }
        }
        // 电子卡类型数据回显
        this.cardTypeList = newValue.ruleData.cardType
          ? newValue.ruleData.cardType.split(",")
          : [];

        // 活动时间范围数据回显  如果直接通过  this.timeSetting.activityTimeRange[0] 这种下标形式赋值的话，会不生效的，因为vue2监控不了这种形式的修改
        let timeArr = [
          newValue.ruleData.activityTimeStart,
          newValue.ruleData.activityTimeEnd,
        ];
        this.timeSetting.activityTimeRange = timeArr;

        // 支付方式回显
        this.timeSetting.periodType = newValue.ruleData.periodType
          ? newValue.ruleData.periodType.split(",")
          : "";

        // 星期、 周生效时间数据回显
        let weekTimelist = [];
        if (newValue.ruleData.weekEffectiveTimeStart) {
          this.timeSetting.weeks = newValue.ruleData.weeklySelection
            .split(",")
            .map((item) => Number(item));
          weekTimelist[0] = newValue.ruleData.weekEffectiveTimeStart;
          weekTimelist[1] = newValue.ruleData.weekEffectiveTimeEnd;
          this.timeSetting.weeksTime = weekTimelist;
        }

        // 月日期、生效时间 回显
        let monthlist = [];
        if (newValue.ruleData.monthEffectiveTimeStart) {
          this.timeSetting.days = newValue.ruleData.monthlySelection
            .split(",")
            .map((item) => Number(item));
          monthlist[0] = newValue.ruleData.monthEffectiveTimeStart;
          monthlist[1] = newValue.ruleData.monthEffectiveTimeEnd;
          this.timeSetting.daysTime = monthlist;
        }
        // 按天执行
        this.timeSetting.monthTimeRangeType = newValue.ruleData.monthTimeRangeType
        this.timeSetting.weekTimeRangeType = newValue.ruleData.weekTimeRangeType
      }

      this.$nextTick(() => {
        this.$refs.ruleDataFormRef.clearValidate();
      });
    },
    "ruleData.sendFlag": {
      handler(newValue) {
        if (newValue === 0) {
          this.$set(this.ruleData, 'wxContent', '')
          // this.ruleData.wxContent = ""; //清空输入框
        }
      },
      deep: true,
    },
  },
  methods: {
    formmatType(type) {
      const types = {
        0: "通用卡",
        1: "汽油卡",
        2: "柴油卡",
        4: "CNG卡",
        3: "LNG卡",
      };
      return types[type] || "";
    },
    async init() {
      const res = await selectCustomerCardSetting();
      this.cardOilsTypeList = res.data.cardOilsTypeList;

    },
    // 清除数据消费
    clearingData() {
      this.formConsumption = {
        accordingTo: "amount",
        settingRuleType: "",
        contentList: [
          {
            presentAmount: undefined,
            rechargeAmtLowerLimit: undefined,
            rechargeAmtUpperLimit: undefined,
          },
        ],
      };
      this.amount = true;
      this.litres = false;
    },

    // 点击编辑
    consumptionHandleEdit() {
      console.log("点击编辑");
    },
    //  消费类型时 的 新增 按钮
    consumptionHandleAdd() {
      let add = 0;
      // 校验消费的表单
      this.$refs.formConsumptionRef.validate((res) => {
        if (!res) {
          add++;
        }
      });

      // 校验充值表单
      this.$refs.ruleDataFormRef.validateField(
        ["enterpriseId", "stationId", "activityMode", "cardType"],
        (res) => {
          if (res) {
            add++;
          }
        }
      );
      if (add === 0) {
        this.$confirm(`确认保存活动吗？`).then(() => {
          const params = {
            enterpriseId: this.ruleData.enterpriseId,
            stationId: this.ruleData.stationId,
            activityMode: this.ruleData.activityMode,
            payType: this.ruleData.payType,
            ...this.formConsumption,
          };
          // 电子卡类型
          params.cardType = this.cardTypeList.join(",");
          // 活动时间范围
          params.activityTimeStart = this.timeSetting.activityTimeRange[0];
          params.activityTimeEnd = this.timeSetting.activityTimeRange[1];
          // 时段类型 按月 按周 按月
          params.periodType = this.timeSetting.periodType.join(",");
          // 周时间
          params.weeklySelection = this.timeSetting.weeks.join(",");
          // 周生效时间
          if (this.timeSetting.weeksTime.length) {
            params.weekEffectiveTimeStart = this.timeSetting.weeksTime[0];
            params.weekEffectiveTimeEnd = this.timeSetting.weeksTime[1];
          }
          // 月时间
          params.monthlySelection = this.timeSetting.days.join(",");
          // 月生效时间
          if (this.timeSetting.daysTime.length) {
            params.monthEffectiveTimeStart = this.timeSetting.daysTime[0];
            params.monthEffectiveTimeEnd = this.timeSetting.daysTime[1];
          }
            // 按天执行
            params.weekTimeRangeType = this.timeSetting.weekTimeRangeType
          params.monthTimeRangeType = this.timeSetting.monthTimeRangeType

          addConsumeActivity(params).then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.msg);
              this.drawer.show = false;
              this.$emit("getData");
              this.clearingData();
            } else {
              this.$message.error(res.msg);
            }
          });
        });
      } else {
        console.log("验证不通过1", this.formConsumption);
        console.log("验证不通过2", this.ruleData);
      }
    },
    // 按金额
    changeAmount(e) {
      if (e) {
        this.litres = false;
        this.formConsumption.accordingTo = "amount";
      } else {
        this.litres = true;
        this.formConsumption.accordingTo = "litres";
      }
    },
    // 按升数
    changeLitres(e) {
      if (e) {
        this.amount = false;
        this.formConsumption.accordingTo = "litres";
      } else {
        this.amount = true;
        this.formConsumption.accordingTo = "amount";
      }
    },
    // 点击取消
    consumptionHandleClone() {
      this.clearingData();
      this.handleClose();
      console.log("点击取消");
    },
    // 增加赠送区间
    addContentList() {
      this.formConsumption.contentList.push({
        presentAmount: undefined,
        rechargeAmtLowerLimit: undefined,
        rechargeAmtUpperLimit: undefined,
      });
    },
    // 删除期间
    popContentList() {
      this.formConsumption.contentList.pop();
    },
    // 验证小数点
    isDecimal(num) {
      let data = {};
      data.x = String(num).indexOf(".") + 1;
      data.y = String(num).length - data.x;
      return data;
    },

    // 匹配两位小数点
    isDecimal2(number) {
      console.log("匹配小数点111");
      let num = parseFloat(number);
      const pattern = /^\d+(\.\d{1,2})?$/; //  两位小数点
      if (!pattern.test(num)) {
        return false;
      } else {
        return true;
      }
    },

    // 根据油企获取油站
    handleSelectChange(value) {
      this.settingData.stationList = [];
      this.getStationList(value);
    },
    // 获取油站
    getStationList(val) {
      listEnterpriseStation({ enterpriseId: val }).then((res) => {
        this.settingData.stationList = res;
      });
    },
    // memberChange(val) {
    //   this.$forceUpdate();
    // },

    // 添加的某个活动规则
    contentListAdd(index) {
      console.log(index);
      this.ruleData.contentList.push({});
    },

    // 删除某个活动规则
    contentListDel(index) {
      this.ruleData.contentList.splice(index, 1);
    },

    // 关闭抽屉
    handleClose() {
      this.clearingData();
      this.$refs.ruleDataFormRef.clearValidate();
      // this.resetForm("ruleDataFormRef"); // 这个重置的话，好像新增和查看之间来回切换时关闭抽屉有问题的的
      this.isCharge = true; // 表单默认归为充值
      this.drawer.show = false;
      this.payMode = [];
      this.ruleData.cardType = "";
      this.cardTypeList = [];
      // 初始化活动时间设置
      this.timeSetting = {
        monthTimeRangeType: 'each',// 月
        weekTimeRangeType: 'each', // 周
        activityTimeRange: [], // 活动时间范围
        periodType: ["all"], // 时段类型  all：全部  ；   week：按周  month按月
        weeks: [], // 按周选择保存周一 到 周日
        weeksTime: "", // 按周生效时间范围
        days: [], // 保存 按月选择的 1-31号的
        daysTime: "", // 按月选择的生效时间范围
      };
      // this.handleClone();
    },

    // 充值时 提交按钮
    handleSubmitAdd() {
      console.log(1111, "提交按钮", this.$refs);

      this.$refs.ruleDataFormRef.validate((valid) => {
        if (valid) {
          console.log("校验通过");
          let params = { ...this.ruleData };
          // 电子卡类型
          params.cardType = this.cardTypeList.join(",");
          // 活动时间范围
          params.activityTimeStart = this.timeSetting.activityTimeRange[0];
          params.activityTimeEnd = this.timeSetting.activityTimeRange[1];
          // 时段类型 按月 按周 按月
          params.periodType = this.timeSetting.periodType.join(",");
          // 周时间
          params.weeklySelection = this.timeSetting.weeks.join(",");
          // 周生效时间
          if (this.timeSetting.weeksTime.length) {
            params.weekEffectiveTimeStart = this.timeSetting.weeksTime[0];
            params.weekEffectiveTimeEnd = this.timeSetting.weeksTime[1];
          }
          // 月时间
          params.monthlySelection = this.timeSetting.days.join(",");
          // 月生效时间
          if (this.timeSetting.daysTime.length) {
            params.monthEffectiveTimeStart = this.timeSetting.daysTime[0];
            params.monthEffectiveTimeEnd = this.timeSetting.daysTime[1];
          }
          // 按天执行
          params.weekTimeRangeType = this.timeSetting.weekTimeRangeType
          params.monthTimeRangeType = this.timeSetting.monthTimeRangeType
          // console.log("电子卡活动参数33333", params);

          this.$confirm(`确认保存活动吗？`).then(() => {
            customerDetail(params).then((res) => {
              if (res && res.code === 200) {
                this.$message.success(res.msg);
                this.handleClose();
                this.$emit("getData");
              } else {
                this.$message.error(res.msg);
              }
            });
          });
        } else {
          console.log("校验不通过");
        }
      });
    },

    //切换活动形式
    inputRadioActivity() {
      this.$refs.ruleDataFormRef.validateField(["activityMode"]);
      // 消费
      if (this.ruleData.activityMode === "consume") {
        this.payMode = [];
        this.isCharge = false;
        // 充值
      } else if (this.ruleData.activityMode === "recharge") {
        this.clearingData();
        this.payMode = [];
        this.isCharge = true;
      }
    },
    // 点击多选框
    inputRadioMethodPayment() {
      this.$refs.ruleDataFormRef.validateField(["payMode"]);
      this.ruleData.payType = this.payMode.join();
    },
    // 改变时间
    changeTimeMode(val) {
      if (val.length === 0) {
        this.timeSetting.weeks = []; // 清空周选择
        this.timeSetting.days = []; // 清空 月选择
      }
      if (!val.includes("week")) {
        this.timeSetting.weeks = [];
      } else if (!val.includes("month")) {
        this.timeSetting.days = [];
      }
    },
  },
};
</script>
<style scoped lang="scss">
.span-yan {
  height: 40px;
  line-height: 40px;
  margin: 0px 50px 0px 10px;
}
.span-yang {
  width: 60px;
  height: 40px;
  line-height: 40px;
  margin-left: 10px;
}
.span-div-qj {
  margin-right: 507px;
}
.span-div {
  margin: 30px 0px;
  width: 100%;
  font-size: 15px;
  display: flex;
  flex-direction: row;
}
.span-text {
  margin-right: 30px;
}

::v-deep.el-checkbox-button {
  margin-right: 40px;

  .el-checkbox-button__inner {
    text-align: center;
    line-height: 35px;
    padding: 0px;
    width: 125px;
    height: 35px;
    color: #409eff;
    border: 1px solid #409eff !important;
    border-radius: 5px;
  }
}
::v-deep.el-checkbox-button.is-checked .el-checkbox-button__inner {
  color: #fff !important;
  background-color: #409eff;
}
::v-deep.el-radio-button {
  margin-right: 40px;

  .el-radio-button__inner {
    // background-color: #ffac40;
    //修改按钮样式
    text-align: center;
    line-height: 35px;
    padding: 0px;
    width: 125px;
    height: 35px;
    color: #409eff;
    border: 1px solid #409eff !important;
    border-radius: 5px;
  }
  .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    // 修改按钮激活样式
    color: #fff;
    background-color: #409eff;
    border-color: #409eff;
  }
}

.radio-activity {
  margin-bottom: 20px;
}

.title_line {
  position: relative;
  font-size: 23px;
}
.title_line::after {
  content: "";
  display: block;
  position: absolute;
  height: 20px;
  width: 5px;
  top: 4px;
  left: -10px;
  background-color: rgba(242, 131, 0, 1);
}

::v-deep .add-drawer {
  overflow-y: auto;
}

.title1 {
  width: 54px;
  height: 50px;
  font-size: 12px;
  margin-right: 20px;
  margin-left: 30px;
}
// 时间按钮样式
::v-deep .numberBtn {
  // padding: 20px 20px 0 20px;
  display: inline-block;
  .block {
    .el-checkbox-group {
      max-width: 90%;
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      .el-checkbox-button {
        margin-right: 3px;
        .el-checkbox-button__inner {
          width: 35px;
        }
      }
    }
  }
}
</style>
